home *** CD-ROM | disk | FTP | other *** search
- ===========================================================================
- BBS: The Abacus * HST/DS * Potterville, MI
- Date: 06-06-93 (21:18) Number: 199
- From: DAVID JOHNSON Refer#: 177
- To: GEOFFREY LIU Recvd: NO
- Subj: Problems with qsort Conf: (36) C Language
- ---------------------------------------------------------------------------
- GL> I hope someone here can point out what I'm doing wrong. I'm
- GL>trying to sort a structure with one of the elements as the "item" being
- GL>sorted. Here's the code:
-
- You can't do it the way you want.. as you have to swap the elements of the struc
- ture. If you sort on the NAME only then the ZIP will be out of place.
-
- here is another version
-
- /*Author: David Johnson */
- /*Copyright: Released to the Public Domain */
-
- /* Structure Sorting routine example */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct address {
- int zip;
- char name[4];
- int nothing;
- };
- /* Prototypes */
- struct address list[5]= { 0,"cat",0,1, "car",1, 2,"cab",2, 3,"cap",3
- , 4,"can",4 };
- void qs_struct(struct address item, int left, int right); void quick_struct(stru
- ct address item[],int count); void swap_all_fields(struct address item[],int i,i
- nt j);
-
-
- main()
- {
- int counter=0;
- quick_struct(&list[0],5);
- for (counter=0;counter<4;counter++) printf("%s\n",list[counter].name); return 0;
- }
-
-
- void quick_struct( struct address item[],int count) /* setup */ { qs_struct(ite
- m[0],0,count-1); }
-
- void qs_struct( struct address address, int left, int right) { register int i,j,
- l; char *x, *y; i=left; j=right; x=list[(left+right)/2].name; do
- {
- while(strcmp(list[i].name,x)<0 && i<right) i++;
- while(strcmp(list[j].name,x)>0 && j>left) j--;
- if (i<=j) {
- swap_all_fields( list,i,j);
- i++;j--;
- }
- } while(i<=j);
-
- if (left<j) qs_struct(address,left,j);
- if (i<right) qs_struct(address,i,right); }
-
- void swap_all_fields(struct address list[],int i,int j) { struct address swap; s
- wap.zip=list[i].zip; strcpy(swap.name,list[i].name); swap.nothing=list[i].nothin
- g;
-
- list[i].zip=list[j].zip;
- strcpy(list[i].name,list[j].name);
- list[i].nothing=list[j].nothing;
-
- list[j].zip=swap.zip;
- strcpy(list[j].name,swap.name);
- list[j].nothing=swap.nothing;
-
- }
-
- ===
- * TLX v2.00 * Every time I make my mark, someone paints the wall...
-
- * DeLuxe2/386 1.25 #483 *
-
- --- DB 1.53/002503
- * Origin: Programmer's Guild BBS - Hamilton, Ont. (416)525-7616 (1:244/117)
- SEEN-BY: 1/211 11/2 4 13/13 101/1 108/89 109/25 110/69 114/5 123/19 124/1
- SEEN-BY: 153/752 154/40 77 157/110 159/100 125 430 575 950 203/23 209/209
- SEEN-BY: 261/1023 280/1 390/1 396/1 5 15 2270/1 2440/5 3603/20
-